#!/usr/bin/env python


import sys
import os
import subprocess


''' Linux From Scratch

Step 1. Build cross tools
'''

# Tools
WGET = 'wget'     
#WGET_ARGS = '-bq'   # Run wget in background quiet mode
WGET_ARGS = ''
MD5SUM = 'md5sum'

package_list = []
package = {'name'       : '', 
           'file'       : '',
           'version'    : '', 
           'size'       : 0, 
           'home'       : '', 
           'url'        : '', 
           'md5sum'     : ''}

class Package(object):
    def __init__(self, pkg_file=None):
        object.__init__(self)

        self.package_list = []
        self.package_template = {
            'name'       : '', 
            'file'       : '',
            'version'    : '', 
            'size'       : 0, 
            'home'       : '', 
            'url'        : '', 
            'md5sum'     : ''
        }

        if pkg_file:
            self.read_pkg_file(pkg_file)

    def read_pkg_file(self, pkg_file):
        try:
            ifile = file(pkg_file, 'r')
        except IOError, e:
            print 'IOError :', e
            sys.exit(-1)

        for i in ifile.read().split('\n\n')[:-1]:
            d = dict(self.package_template)
            #i.strip()
            j = i.strip().split('\n')
            l = [x.strip() for x in j]      # Strip each item in the list
            k = l[0].split(' ')
            d['name'] = k[0].strip()
            d['version'] = k[1][1:-1]
            # Bug here, can't get size
            #d['size'] = j[0].split(' - ')[-1].split(' ')[0].replace(',', '')
            d['size'] = 0
            d['home'] = l[1].split(' ')[-1]
            d['url'] = l[2].split(' ')[-1]
            d['file'] = l[2].split('/')[-1]
            d['md5sum'] = l[3].split(' ')[-1]
            self.package_list.append(d)
            #print d

        ifile.close()
        del ifile

    def download_packages(self, pkg):
        try:
            p= subprocess.Popen([WGET, WGET_ARGS, pkg['url']], stdout = sys.stdout)
        except ValueError, e:
            print 'ValueError, ', e
            pass
        except OSError, e:
            print 'OSError, ', e
            pass
        s = os.waitpid(p.pid, 0)[1]

    def check_md5sum(self, pkg):
        try:
            p = subprocess.Popen([MD5SUM, pkg['name']], stdout=subprocess.PIPE)
        except ValueError, e:
            print 'ValueError, ', e
        except OSError, e:
            print 'OSError, ', e
        md5sum = p.communicate()[0].split(' ')[0]

        print type(md5sum), '----', type(pkg['md5sum'])
        return md5sum == pkg['md5sum']

    def download(self):
        for pkg in self.package_list:
            self.download_packages(pkg)
            #if not self.check_md5sum(pkg['md5sum']):


def main():
    os.system('clear')

    pkg = Package('pkgs.txt')
    pkg.download()

if __name__ == '__main__':
    main()

